package com.llyb.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.llyb.tingshu.common.constant.SystemConstant;
import com.llyb.tingshu.common.rabbit.constant.MqConst;
import com.llyb.tingshu.common.rabbit.service.RabbitService;
import com.llyb.tingshu.common.util.MongoUtil;
import com.llyb.tingshu.model.user.UserListenProcess;
import com.llyb.tingshu.user.service.UserListenProcessService;
import com.llyb.tingshu.vo.album.TrackStatMqVo;
import com.llyb.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitService rabbitService;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {

        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));

        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);

        if (null != userListenProcess) {
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setUpdateTime(new Date());
        } else {
            userListenProcess = new UserListenProcess();
            userListenProcess.setUserId(userId);
            userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            userListenProcess.setTrackId(userListenProcessVo.getTrackId());
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
            userListenProcess.setIsShow(1);
        }
        mongoTemplate.save(userListenProcess, collectionName);

        // 防止用户恶意刷单  一天只能更新一次播放记录
        // 分布式锁解决

        String key = userId + ":lock:track:" + userListenProcessVo.getTrackId();
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, "1", 1, TimeUnit.DAYS);
        if (ifAbsent) {
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setCount(1);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            trackStatMqVo.setBusinessNo(uuid);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,
                    MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));

        }

    }

    @Override
    public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {

        String collectionName = MongoUtil
                .getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = Query.query(Criteria.where("trackId").is(trackId)).limit(1);

        // 获取播放记录
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);

        if (null != userListenProcess) {
            return userListenProcess.getBreakSecond();
        }

        return new BigDecimal(0);
    }

    @Override
    public Map<String, Object> getLatelyTrack(Long userId) {

        Map<String, Object> map = new HashMap<>();
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = Query.query(Criteria.where("isShow").is(1)).limit(1)
                .with(Sort.by(Sort.Order.desc("updateTime")));
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        if (null != userListenProcess) {
            map.put("albumId", userListenProcess.getAlbumId());
            map.put("trackId", userListenProcess.getTrackId());
            return map;
        }
        return null;
    }
}
